package com.rds.benchmark.operator;

import com.rds.benchmark.util.MakeValue;
import org.redisson.api.RBucket;

import java.io.IOException;
import java.util.Date;

public class StableStringRedissonOperator extends TypeOperatorBase {

    private RBucket<Object> conn;

    private String key;

    private static long ErrorTimestamp = 0;

    private final String value = MakeValue.value;

    private synchronized boolean needPrint() {
        long timestamp = System.currentTimeMillis() / 2000;
        if (timestamp != ErrorTimestamp) {
            ErrorTimestamp = timestamp;
            return true;
        }
        return false;
    }

    @Override
    public void init(Object conn, String key, int idx,String mode) {
        this.conn = (RBucket<Object>) conn;
        this.key = key;
        this.conn.set(value);
    }

    @Override
    public Long clear() {
        return conn.delete() ? 1 : 0L;
    }

    @Override
    public void operate() throws IOException {
        try {
            ++times;
            conn.get();
        } catch (Throwable t) {
            if (needPrint()) {
                System.out.println(new Date() + " ERROR: " + t.getMessage());
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
    }
}
